<!DOCTYPE html><html class="theme-next gemini use-motion" lang="zh-CN"><head><meta name="generator" content="Hexo 3.9.0"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2"><link rel="stylesheet" href="/css/main.css?v=7.1.1"><link rel="apple-touch-icon" sizes="180x180" href="/images/my-apple-touch-icon-next.png?v=7.1.1"><link rel="icon" type="image/png" sizes="32x32" href="/images/my-32x32-next.png?v=7.1.1"><link rel="icon" type="image/png" sizes="16x16" href="/images/my-16x16-next.png?v=7.1.1"><link rel="mask-icon" href="/images/my-logo.svg?v=7.1.1" color="#222"><script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script><meta name="description" content="指针是 C 语言中的一大难点，本文会对指针的类型解析，指针的算术运算，指针的赋值取值，指针的应用场景等方面一步步探索指针的奥妙，揭开指针神秘的面纱。"><meta name="keywords" content="C语言,指针,指针应用,C"><meta property="og:type" content="article"><meta property="og:title" content="C指针总结"><meta property="og:url" content="https://renshengjihe.cn/190613-CPointer.html"><meta property="og:site_name" content="dhd的博客"><meta property="og:description" content="指针是 C 语言中的一大难点，本文会对指针的类型解析，指针的算术运算，指针的赋值取值，指针的应用场景等方面一步步探索指针的奥妙，揭开指针神秘的面纱。"><meta property="og:locale" content="zh-CN"><meta property="og:image" content="https://renshengjihe.cn/190613-CPointer/2_1.png"><meta property="og:image" content="https://renshengjihe.cn/190613-CPointer/5_1.png"><meta property="og:image" content="https://renshengjihe.cn/190613-CPointer/6_1.png"><meta property="og:updated_time" content="2019-11-18T07:46:11.985Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="C指针总结"><meta name="twitter:description" content="指针是 C 语言中的一大难点，本文会对指针的类型解析，指针的算术运算，指针的赋值取值，指针的应用场景等方面一步步探索指针的奥妙，揭开指针神秘的面纱。"><meta name="twitter:image" content="https://renshengjihe.cn/190613-CPointer/2_1.png"><link rel="canonical" href="https://renshengjihe.cn/190613-CPointer"><script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script><title>C指针总结 | dhd的博客</title><noscript><style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style></noscript></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">dhd的博客</span><span class="logo-line-after"><i></i></span></a></div><h1 class="site-subtitle" itemprop="description">对酒当歌，人生几何</h1></div><div class="site-nav-toggle"> <button aria-label="切换导航栏"><span class="btn-bar"></span><span class="btn-bar"></span><span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档</a></li></ul></nav></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="https://renshengjihe.cn/190613-CPointer.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="dhd"><meta itemprop="description" content="个人博客,分享一些C/C++ Linux 相关的学习笔记"><meta itemprop="image" content="/images/avatar.gif"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="dhd的博客"></span><header class="post-header"><h2 class="post-title" itemprop="name headline">C指针总结</h2><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i></span> <span class="post-meta-item-text">发表于</span> <time title="创建时间：2019-06-13 10:31:57" itemprop="dateCreated datePublished" datetime="2019-06-13T10:31:57+08:00">2019-06-13</time> <span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i></span> <span class="post-meta-item-text">更新于</span> <time title="修改时间：2019-11-18 15:46:11" itemprop="dateModified" datetime="2019-11-18T15:46:11+08:00">2019-11-18</time></span> <span class="post-category"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-folder-o"></i></span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/C-C/" itemprop="url" rel="index"><span itemprop="name">C/C++</span></a></span></span> <span class="post-comments-count"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-comment-o"></i></span> <span class="post-meta-item-text">评论数：</span><a href="/190613-CPointer.html#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/190613-CPointer.html" itemprop="commentCount"></span></a></span> <span id="/190613-CPointer.html" class="leancloud_visitors" data-flag-title="C指针总结"><span class="post-meta-divider">|</span><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数：</span><span class="leancloud-visitors-count"></span></span><div class="post-description">指针是 C 语言中的一大难点，本文会对指针的类型解析，指针的算术运算，指针的赋值取值，指针的应用场景等方面一步步探索指针的奥妙，揭开指针神秘的面纱。</div></div></header><div class="post-body" itemprop="articleBody"><p>指针是 C 语言中的一大难点，本文会对指针的类型解析，指针的算术运算，指针的赋值取值，指针的应用场景等方面一步步探索指针的奥妙，揭开指针神秘的面纱。</p><a id="more"></a><h2 id="识别各种各样的指针"><a href="#识别各种各样的指针" class="headerlink" title="识别各种各样的指针"></a>识别各种各样的指针</h2><h3 id="单指针"><a href="#单指针" class="headerlink" title="单指针"></a>单指针</h3><ul><li>单指针很好理解，就是一个指向内存空间地址的变量；</li><li>指针变量的大小取决于所用机子的寻址方式，与所指内容无关，一般 32 位系统为 4 个字节，64 位系统为 8 个字节。</li></ul><p>单指针定义与使用的方式如下<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a = <span class="number">0</span>;      </span><br><span class="line"><span class="keyword">int</span> *p = &amp;a;    <span class="comment">// 定义并初始化指针p</span></span><br><span class="line"><span class="keyword">int</span> b = *p;     <span class="comment">// 取指针p的值</span></span><br></pre></td></tr></table></figure><p></p><h3 id="二级指针"><a href="#二级指针" class="headerlink" title="二级指针"></a>二级指针</h3><ul><li>二级指针（又称二重指针，emmm，随便怎么叫吧）就是指针的指针；</li><li>与普通的单指针相比仅仅是所指向内容上的不同。</li></ul><p>二级指针定义与使用的方式如下<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">int</span> *p = &amp;a;    <span class="comment">// 定义并初始化指针p</span></span><br><span class="line"><span class="keyword">int</span> *pp = &amp;p;   <span class="comment">// 定义并初始化二重指针p</span></span><br><span class="line"><span class="keyword">int</span> *q = *pp;   <span class="comment">// 对pp取值得到的是一个整形指针</span></span><br><span class="line"><span class="keyword">int</span> b = **pp;   <span class="comment">// 对pp两次取值得到的是一个整形数据</span></span><br></pre></td></tr></table></figure><p></p><p>既然有二级指针，当然有三级、四级、五级……就不一一分析了，而且实际应用中也不会涉及太多级的指针。</p><h3 id="数组指针"><a href="#数组指针" class="headerlink" title="数组指针"></a>数组指针</h3><p>数组指针又称行指针，即指向数组的指针。其定义与使用方式如下<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> arr[][<span class="number">2</span>] = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;;</span><br><span class="line"><span class="keyword">int</span> (*p)[<span class="number">2</span>] = arr;</span><br><span class="line"><span class="keyword">int</span> a = p[<span class="number">0</span>][<span class="number">1</span>];</span><br></pre></td></tr></table></figure><p></p><p>指针数组与数组指针写法类似，其定义与使用方法如下<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> *arr[<span class="number">3</span>] = &#123;<span class="number">0</span>&#125;;</span><br><span class="line"><span class="keyword">int</span> *p = arr[<span class="number">1</span>];</span><br></pre></td></tr></table></figure><p></p><ul><li>数组指针本质是指针，其指向一个数组内存空间的首地址</li><li>指针数组本质是数组，数组中的元素是指针</li></ul><p>可以通过向右优先结合的方式来判断复杂指针的类型，如<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 从p开始向右，先与[]结合，可知是一个数组。</span></span><br><span class="line"><span class="comment">// 然后向左结合，可知数组中存的是指针</span></span><br><span class="line"><span class="comment">// 继续向左，指针指向的数据类型是int</span></span><br><span class="line"><span class="keyword">int</span> *p[<span class="number">3</span>] = &#123;<span class="number">0</span>&#125;;</span><br></pre></td></tr></table></figure><p></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 从p开始向右，遇到右括号，先结合括号内的*,可知是一个指针</span></span><br><span class="line"><span class="comment">// 向右结合，可知指针指向的是一个数组</span></span><br><span class="line"><span class="comment">// 再向左结合，可知指针指向一个int型的数组</span></span><br><span class="line"><span class="keyword">int</span> (*p)[<span class="number">2</span>] = arr;</span><br></pre></td></tr></table></figure><h3 id="函数指针"><a href="#函数指针" class="headerlink" title="函数指针"></a>函数指针</h3><p>指针也可指向函数，其定义与使用方法如下<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">fun</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// ......</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">int</span> (*p)() = fun;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    p();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>函数指针容易和返回值为指针的函数混淆<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> *<span class="title">fun</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure><p></p><p>同样可以用上述的向右优先结合的方式来一步步分析</p><h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><table><thead><tr><th>类型名</th><th>定义格式</th></tr></thead><tbody><tr><td>单指针</td><td><code>int *p;</code></td></tr><tr><td>二级指针</td><td><code>int **p;</code></td></tr><tr><td>数组指针</td><td><code>int (*p)[2];</code></td></tr><tr><td>指针数组</td><td><code>int *arr[2];</code></td></tr><tr><td>函数指针</td><td><code>int (*p)();</code></td></tr><tr><td>指针函数</td><td><code>int *func();</code></td></tr></tbody></table><h2 id="指针的算术运算"><a href="#指针的算术运算" class="headerlink" title="指针的算术运算"></a>指针的算术运算</h2><ul><li>指针可以加上或减去一个整数；</li><li>此加减以存储单元为单位，取决于指针的基类型大小；</li></ul><p>下面的程序可以看出指针进行算术运算时的变化<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a[] = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>&#125;;</span><br><span class="line">    <span class="keyword">int</span> *p = a;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"%d, %x\n"</span>, *p, p);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"%d, %x\n"</span>, *(p+<span class="number">3</span>), p+<span class="number">3</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>程序执行的结果为：</p><p><img src="/190613-CPointer/2_1.png" alt="图2_1"></p><p>p 和 p+3 之间的内存地址相差 0xc 即 12个 = 3个int的大小</p><h2 id="运算符-amp-和"><a href="#运算符-amp-和" class="headerlink" title="运算符 &amp; 和 *"></a>运算符 &amp; 和 *</h2><ul><li>这里 &amp; 是取地址运算符， * 是间接运算符。</li><li>&amp;a 的运算结果是一个指针，指针的类型是 a 的类型加个*，指针所<br>指向的类型是 a 的类型，指针所指向的地址就是 a 的地址。</li><li>*p 的结果是 p 所指向的东西，它的类型是 p 指向的类型，它所占用的地址是 p 所指向的地址。</li></ul><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">int</span> *p;</span><br><span class="line"><span class="keyword">int</span> **pp;   </span><br><span class="line">p = &amp;a;     <span class="comment">// 这里 &amp;a 就是 a 的地址</span></span><br><span class="line">*p = <span class="number">1</span>;     <span class="comment">// 这里修改 *p 修改的是 a 的值</span></span><br><span class="line">pp = &amp;p;    <span class="comment">// 这里 &amp;p 就是 p 的地址</span></span><br><span class="line">**p = <span class="number">2</span>;    <span class="comment">// 这里修改 **p 修改的是 a 的值</span></span><br></pre></td></tr></table></figure><h2 id="指针与数组"><a href="#指针与数组" class="headerlink" title="指针与数组"></a>指针与数组</h2><p>数组的数组名其实可以看作一个指针。看下例:<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> arr[] = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;;</span><br><span class="line"><span class="built_in">printf</span>(<span class="string">"%d\n"</span>, *arr);</span><br><span class="line"><span class="built_in">printf</span>(<span class="string">"%d\n"</span>, *(arr+<span class="number">1</span>));</span><br><span class="line"><span class="built_in">printf</span>(<span class="string">"%d\n"</span>, arr[<span class="number">2</span>]);</span><br></pre></td></tr></table></figure><p></p><ul><li>数组的元素可以用 数组名+偏移量 的方式找到；</li><li>同样，一个指向数组首地址的指针也可以用 [] 进行访问。</li></ul><h2 id="指针的类型转换"><a href="#指针的类型转换" class="headerlink" title="指针的类型转换"></a>指针的类型转换</h2><p>指针的类型被强制转换后，其指向的地址不受影响，但其进行算术运算时的大小会发生改变。<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">char</span> *p = (<span class="keyword">char</span> *)&amp;a;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"%x\n"</span>, &amp;a);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"%x\n"</span>, p);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"%x\n"</span>, p+<span class="number">1</span>);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"%x\n"</span>, p+<span class="number">2</span>);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"%x\n"</span>, p+<span class="number">3</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>程序运行的结果是</p><p><img src="/190613-CPointer/5_1.png" alt="图5_1"></p><h2 id="指针的应用场景"><a href="#指针的应用场景" class="headerlink" title="指针的应用场景"></a>指针的应用场景</h2><h3 id="给函数传不定量的参数"><a href="#给函数传不定量的参数" class="headerlink" title="给函数传不定量的参数"></a>给函数传不定量的参数</h3><p>典型的示例就是 main 函数的 argc 和 argv</p><p>下面是一个找最长字符串的命令的实现<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> pos = <span class="number">-1</span>;</span><br><span class="line">    <span class="keyword">int</span> maxLen = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; argc; ++i)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">int</span> len = <span class="built_in">strlen</span>(argv[i]);</span><br><span class="line">        <span class="keyword">if</span>(maxLen &lt; len)</span><br><span class="line">        &#123;</span><br><span class="line">            pos = i;</span><br><span class="line">            maxLen = len;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(pos != <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"pos = %d\n"</span>, pos);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"len = %d\n"</span>, maxLen);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"str = %s\n"</span>, argv[pos]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>程序运行结果如下</p><p><img src="/190613-CPointer/6_1.png" alt="图6_1"></p><h3 id="给排序函数传入比较规则"><a href="#给排序函数传入比较规则" class="headerlink" title="给排序函数传入比较规则"></a>给排序函数传入比较规则</h3><p>以一个选择排序为例，客户程序员可以不需要修改 Sort 函数的内容，只需要改变传入的参数，就可以实现按不同的方式排列。<br></p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 插入排序函数</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Sort</span><span class="params">(<span class="keyword">int</span> *a, <span class="keyword">size_t</span> n, <span class="keyword">bool</span>(*cmp)(<span class="keyword">int</span>, <span class="keyword">int</span>))</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>( <span class="literal">NULL</span> == a )</span><br><span class="line">        <span class="keyword">return</span> ;</span><br><span class="line">    <span class="keyword">int</span> i, j;</span><br><span class="line">    <span class="keyword">for</span>( i = <span class="number">1</span>; i &lt; n; ++i )</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span>( cmp( a[i], a[i<span class="number">-1</span>] ) )</span><br><span class="line">        &#123;</span><br><span class="line">            T tmp = a[i];</span><br><span class="line">            <span class="keyword">for</span>( j = i<span class="number">-1</span>; j &gt;= <span class="number">0</span> &amp;&amp; !cmp( a[j], tmp ); --j )</span><br><span class="line">                a[j+<span class="number">1</span>] = a[j];</span><br><span class="line">            a[j+<span class="number">1</span>] = tmp;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 比较函数</span></span><br><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">compare</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a &lt; b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a[] = &#123;<span class="number">7</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">2</span>, <span class="number">4</span>&#125;;</span><br><span class="line">    <span class="comment">// 函数名作为参数传入</span></span><br><span class="line">    sort(a, <span class="keyword">sizeof</span>(a)/<span class="keyword">sizeof</span>(a[<span class="number">0</span>], compare));</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><h2 id="指针的安全使用"><a href="#指针的安全使用" class="headerlink" title="指针的安全使用"></a>指针的安全使用</h2><p>指针的使用要注意安全性</p><ul><li>要清楚指针到底指向了哪里，不能超出程序所能使用的内存范围，常见的错误如数组越界，强制转换成更大空间的指针（int -&gt; double）等。</li><li>指针使用完毕后要及时至空，以免造成野指针的问题。</li><li>动态分配的内存空间要记得释放，避免发生内存泄露。</li><li>不要给指针直接赋非0数值，除非你在搞贴近硬件的开发，并且清楚对应的地址代表着什么。</li></ul></div><footer class="post-footer"><div class="post-tags"> <a href="/tags/C-C/" rel="tag"># C/C++</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/190528-TinyHttpdSourceCode.html" rel="next" title="Tinyhttpd源码解析"><i class="fa fa-chevron-left"></i> Tinyhttpd源码解析</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"> <a href="/190616-CCppByteAlign.html" rel="prev" title="C/C++字节对齐">C/C++字节对齐<i class="fa fa-chevron-right"></i></a></div></div></footer></div></article></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span><span class="sidebar-toggle-line sidebar-toggle-line-middle"></span><span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap"> 文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap"> 站点概览</li></ul><div class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><p class="site-author-name" itemprop="name">dhd</p><div class="site-description motion-element" itemprop="description">个人博客,分享一些C/C++ Linux 相关的学习笔记</div></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"> <a href="/archives/"><span class="site-state-item-count">16</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"> <a href="/categories/"><span class="site-state-item-count">7</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"> <a href="/tags/"><span class="site-state-item-count">8</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="mailto:donghaodong555@foxmail.com" title="E-Mail &rarr; mailto:donghaodong555@foxmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a></span></div></div></div><div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#识别各种各样的指针"><span class="nav-number">1.</span> <span class="nav-text">识别各种各样的指针</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#单指针"><span class="nav-number">1.1.</span> <span class="nav-text">单指针</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二级指针"><span class="nav-number">1.2.</span> <span class="nav-text">二级指针</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数组指针"><span class="nav-number">1.3.</span> <span class="nav-text">数组指针</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数指针"><span class="nav-number">1.4.</span> <span class="nav-text">函数指针</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">1.5.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#指针的算术运算"><span class="nav-number">2.</span> <span class="nav-text">指针的算术运算</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#运算符-amp-和"><span class="nav-number">3.</span> <span class="nav-text">运算符 &amp; 和 *</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#指针与数组"><span class="nav-number">4.</span> <span class="nav-text">指针与数组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#指针的类型转换"><span class="nav-number">5.</span> <span class="nav-text">指针的类型转换</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#指针的应用场景"><span class="nav-number">6.</span> <span class="nav-text">指针的应用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#给函数传不定量的参数"><span class="nav-number">6.1.</span> <span class="nav-text">给函数传不定量的参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#给排序函数传入比较规则"><span class="nav-number">6.2.</span> <span class="nav-text">给排序函数传入比较规则</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#指针的安全使用"><span class="nav-number">7.</span> <span class="nav-text">指针的安全使用</span></a></li></ol></div></div></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">&copy; <span itemprop="copyrightYear">2019</span><span class="with-love" id="animate"><i class="fa fa-user"></i></span> <span class="author" itemprop="copyrightHolder">dhd</span></div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i></div></div><script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script><script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="/lib/canvas-nest/canvas-nest.min.js"></script><script src="/lib/jquery/index.js?v=2.1.3"></script><script src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script src="/js/utils.js?v=7.1.1"></script><script src="/js/motion.js?v=7.1.1"></script><script src="/js/affix.js?v=7.1.1"></script><script src="/js/schemes/pisces.js?v=7.1.1"></script><script src="/js/scrollspy.js?v=7.1.1"></script><script src="/js/post-details.js?v=7.1.1"></script><script src="/js/next-boot.js?v=7.1.1"></script><script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script><script src="//unpkg.com/valine/dist/Valine.min.js"></script><script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'f6cPnWydCEaioX6iq6AoSBPz-gzGzoHsz',
    appKey: 'TRF9THIRqNFdQRvrCURnmfBG',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: '' || 'zh-cn'
  });
</script><script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'hrnLXd6od62r2eJJ9yYsWO74-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'hrnLXd6od62r2eJJ9yYsWO74-gzGzoHsz',
                'X-LC-Key': 'N3zDUUUGyqewKV2RLoozARF2',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script><script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script><script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script></body></html>